package org.jeecg.modules.couteachingjobexecute.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.common.baseentity.BaseApiEntity;
import org.jeecg.modules.common.utils.DateUtil;
import org.jeecg.modules.couteachingjobexecute.entity.CouTeachingJobExecute;
import org.jeecg.modules.couteachingjobexecute.service.ICouTeachingJobExecuteService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.couteachingjobexecute.vo.CouTeachingJobExecuteVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: cou_teaching_job_execute
 * @author: baochangrong
 * @Date: 2022-04-11
 * @Version: V1.0
 */
@Api(tags = "cou_teaching_job_execute")
@RestController
@RequestMapping("/couteachingjobexecute/couTeachingJobExecute")
@Slf4j
public class CouTeachingJobExecuteController extends JeecgController<CouTeachingJobExecute, ICouTeachingJobExecuteService> {
    @Autowired
    private ICouTeachingJobExecuteService couTeachingJobExecuteService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    /**
     * 分页列表查询
     *
     * @param couTeachingJobExecute
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "cou_teaching_job_execute-查询默认当前周次")
    @ApiOperation(value = "cou_teaching_job_execute-查询默认当前周次", notes = "cou_teaching_job_execute-查询默认当前周次")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CouTeachingJobExecute couTeachingJobExecute,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CouTeachingJobExecute> queryWrapper = QueryGenerator.initQueryWrapper(couTeachingJobExecute, req.getParameterMap());
        Page<CouTeachingJobExecute> page = new Page<CouTeachingJobExecute>(pageNo, pageSize);
//        List orderbys = new ArrayList<>();
//        orderbys.add("teaching_job_exe_date");
//        orderbys.add("week_set_index");
//        orderbys.add("teaching_job_exe_week");
//        orderbys.add("teaching_job_exe_new_week");
//        orderbys.add("teaching_job_exe_section");
//        queryWrapper.orderBy(true,true,orderbys);
        queryWrapper.eq("teaching_job_exe_date", DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
//        IPage<CouTeachingJobExecute> pageList = couTeachingJobExecuteService.page(page, queryWrapper);
        CouTeachingJobExecute teachingJobExecute = couTeachingJobExecuteService.getOne(queryWrapper, false);
        return Result.OK(teachingJobExecute);
    }

    /**
     * 教学计划执行数据查询
     * <p>
     * 后期查询固定使用此类型方法，不关心查询条件，只需要校验必填条件即可。后续方法中一路传couTeachingJobExecutePage对象，
     * 包括xml里面也用couTeachingJobExecutePage类型传入，
     * 非对象类型的返回也直接使用couTeachingJobExecute返回。如果是页面表单展示则使用对象，这样保证前后端字段一致。看模板步骤
     *
     * @param couTeachingJobExecuteVo
     * @param req
     * @return
     */
    @AutoLog(value = "cou_teaching_job_execute-教学计划执行数据查询")
    @ApiOperation(value = "cou_teaching_job_execute-教学计划执行数据查询", notes = "cou_teaching_job_execute-教学计划执行数据查询")
    @GetMapping(value = "/listAll")
    public Result<?> queryCouTeachingJobExecuteAll(
            CouTeachingJobExecuteVo couTeachingJobExecuteVo,
            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
            HttpServletRequest req) {
        //一、校验必填查询条件
//        Assert.hasText(couTeachingJobExecuteVo.getGradeId(), "请选择年级！");
//        Assert.hasText(couTeachingJobExecuteVo.getClassId(), "请选择班级");
        Assert.hasText(couTeachingJobExecuteVo.getWeekSetIndex() + "", "查询周次未传递");
        Page<CouTeachingJobExecute> page = new Page(pageNo, pageSize);

        return couTeachingJobExecuteService.queryCouTeachingJobExecuteAll(page, couTeachingJobExecuteVo);
    }

    @AutoLog(value = "cou_teaching_job_execute-查询老师科目统计课时信息")
    @ApiOperation(value = "cou_teaching_job_execute-查询老师科目统计课时信息", notes = "cou_teaching_job_execute-查询老师科目统计课时信息")
    @GetMapping(value = "/getTeacherAndSubjectCount")
    public Result<?> getTeacherAndSubjectCount( CouTeachingJobExecuteVo couTeachingJobExecuteVo,
                                                @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                HttpServletRequest req) {
        //一、校验必填查询条件
        Assert.hasText(couTeachingJobExecuteVo.getSubjectId(), "科目ID不能为空！");
        Assert.hasText(couTeachingJobExecuteVo.getTeacherId(), "老师ID不能为空");
        Assert.hasText(couTeachingJobExecuteVo.getTeachingJobExeDate() + "", "日期不能为空");
        Assert.hasText(couTeachingJobExecuteVo.getGradeId(), "请选择年级！");
        Assert.hasText(couTeachingJobExecuteVo.getClassId(), "请选择班级");

        Page<JSONObject> page = new Page(pageNo, pageSize);

        return couTeachingJobExecuteService.getTeacherAndSubjectCount(page, couTeachingJobExecuteVo);
    }

    @AutoLog(value = "cou_teaching_job_execute-查询老师课时按月统计信息")
    @ApiOperation(value = "cou_teaching_job_execute-查询老师课时按月统计信息", notes = "cou_teaching_job_execute-查询老师课时按月统计信息")
    @GetMapping(value = "/queryTeacherJobDurationDate")
    public Result<?> queryTeacherJobDurationDate(CouTeachingJobExecuteVo couTeachingJobExecuteVo,
                                                 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                 HttpServletRequest req) throws NoSuchFieldException, IllegalAccessException {
        //一、校验必填查询条件
//        Assert.hasText(couTeachingJobExecuteVo.getGradeId(), "请选择年级！");
        Page<CouTeachingJobExecute> page = new Page(pageNo, pageSize);

        return couTeachingJobExecuteService.queryTeacherJobDurationDate(page, couTeachingJobExecuteVo);
    }


    @AutoLog(value = "cou_teaching_job_execute-查询老师课时按周统计信息")
    @ApiOperation(value = "cou_teaching_job_execute-查询老师课时按周统计信息", notes = "cou_teaching_job_execute-查询老师课时按周统计信息")
    @GetMapping(value = "/queryTeacherJobDurationWeekSetIndex")
    public Result<?> queryTeacherJobDurationWeekSetIndex(CouTeachingJobExecuteVo couTeachingJobExecuteVo,
                                                         @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                         @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                         HttpServletRequest req) {
        //一、校验必填查询条件
        Assert.hasText(couTeachingJobExecuteVo.getGradeId(), "请选择年级！");
        Page<CouTeachingJobExecute> page = new Page(pageNo, pageSize);

        return couTeachingJobExecuteService.queryTeacherJobDurationWeekSetIndex(page, couTeachingJobExecuteVo);
    }

    @AutoLog(value = "cou_teaching_job_execute-换课-补课接口")
    @ApiOperation(value = "cou_teaching_job_execute-换课-补课接口", notes = "cou_teaching_job_execute-换课-补课接口")
    @PostMapping(value = "/changeCoures")
    public Result<?> changeCoures(@RequestBody JSONObject jsonInfo, HttpServletRequest req) {
        //一、校验必填查询条件
        Assert.notEmpty(jsonInfo, "请选择换课或者补课对象！");
        return couTeachingJobExecuteService.changeCoures(jsonInfo);
    }

    @AutoLog(value = "cou_teaching_job_execute-代课接口")
    @ApiOperation(value = "cou_teaching_job_execute-代课接口", notes = "cou_teaching_job_execute-代课接口")
    @PostMapping(value = "/changeCouresTeacher")
    public Result<?> changeCouresTeacher(@RequestBody JSONObject jsonInfo, HttpServletRequest req) {
        //一、校验必填查询条件
        Assert.hasText(jsonInfo.getString("newTeacherId"), "请选择代课老师！");
        Assert.notNull(jsonInfo.getJSONObject("oldCouTeachingJobExecute"), "请选择被代课老师！");
        return couTeachingJobExecuteService.changeCouresTeacher(jsonInfo);
    }

    /**
     * 添加
     *
     * @param couTeachingJobExecute
     * @return
     */
    @AutoLog(value = "cou_teaching_job_execute-添加")
    @ApiOperation(value = "cou_teaching_job_execute-添加", notes = "cou_teaching_job_execute-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CouTeachingJobExecute couTeachingJobExecute) {
        couTeachingJobExecuteService.save(couTeachingJobExecute);
        return Result.OK("添加成功！");
    }

    /**
     * 手工生成教学任务执行日期
     *
     * @param couTeachingJobExecuteVo
     * @return
     */
    @AutoLog(value = "cou_teaching_job_execute-手工生成教学任务执行日期")
    @ApiOperation(value = "cou_teaching_job_execute-手工生成教学任务执行日期", notes = "cou_teaching_job_execute-手工生成教学任务执行日期")
    @PostMapping(value = "/runTeachingJobExecute")
    public Result<?> runTeachingJobExecute(@RequestBody CouTeachingJobExecuteVo couTeachingJobExecuteVo, HttpServletRequest req) {


        BaseApiEntity baseApiEntity = this.querySysInfo(req);

        Result result = couTeachingJobExecuteService.runTeachingJobExecute(couTeachingJobExecuteVo, baseApiEntity);
        return result;
    }

    /**
     * 编辑
     *
     * @param couTeachingJobExecute
     * @return
     */
    @AutoLog(value = "cou_teaching_job_execute-编辑")
    @ApiOperation(value = "cou_teaching_job_execute-编辑", notes = "cou_teaching_job_execute-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CouTeachingJobExecute couTeachingJobExecute) {
        couTeachingJobExecuteService.updateById(couTeachingJobExecute);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "cou_teaching_job_execute-通过id删除")
    @ApiOperation(value = "cou_teaching_job_execute-通过id删除", notes = "cou_teaching_job_execute-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        couTeachingJobExecuteService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "cou_teaching_job_execute-批量删除")
    @ApiOperation(value = "cou_teaching_job_execute-批量删除", notes = "cou_teaching_job_execute-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.couTeachingJobExecuteService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "cou_teaching_job_execute-通过id查询")
    @ApiOperation(value = "cou_teaching_job_execute-通过id查询", notes = "cou_teaching_job_execute-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CouTeachingJobExecute couTeachingJobExecute = couTeachingJobExecuteService.getById(id);
        if (couTeachingJobExecute == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(couTeachingJobExecute);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "cou_teaching_job_execute-通过id查询")
    @ApiOperation(value = "cou_teaching_job_execute-通过id查询", notes = "cou_teaching_job_execute-通过id查询")
    @GetMapping(value = "/queryByIdDetail")
    public Result<?> queryByIdDetail(@RequestParam(name = "id", required = true) String id,
                                     @RequestParam(name = "pageNo", required = true) int pageNo,
                                     @RequestParam(name = "pageSize", required = true) int pageSize) {
        //一、校验必填查询条件
        //二、校验分页数据是否传，没有则使用默认值
        CouTeachingJobExecuteVo couTeachingJobExecuteVo = new CouTeachingJobExecuteVo();
        couTeachingJobExecuteVo.setId(id);
        couTeachingJobExecuteVo.setIzOpen(0);

        Page<CouTeachingJobExecute> page = new Page(pageNo, pageSize);

        return couTeachingJobExecuteService.queryByIdDetail(page, couTeachingJobExecuteVo);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param couTeachingJobExecute
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CouTeachingJobExecute couTeachingJobExecute) {
        return super.exportXls(request, couTeachingJobExecute, CouTeachingJobExecute.class, "cou_teaching_job_execute");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CouTeachingJobExecute.class);
    }

    /**
     * 从request获取 token 用户信息，组织信息
     *
     * @param req
     * @return
     */
    public BaseApiEntity querySysInfo(HttpServletRequest req) {

        BaseApiEntity baseApiEntity = new BaseApiEntity();

        //获取当前登录用户信息
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        baseApiEntity.setUsername(username);
        baseApiEntity.setCreateBy(username);
        baseApiEntity.setUpdateBy(username);

        LoginUser loginUser = sysBaseAPI.getUserByName(username); //.getUserById() 获取登录用户
        baseApiEntity.setLoginUser(loginUser);
        String sysOrgCode = loginUser.getOrgCode();//获取当前用户的当前的部门编码（不是id是编码）,该编码随前端切换
        String tenantId = req.getHeader("tenant-id");//获取当前登录用户的租户id
        baseApiEntity.setTenantId(tenantId);

        String departId = sysBaseAPI.getDepartIdsByOrgCode(sysOrgCode);//获取当前用户设置的部门id
        List<String> subDepIdsList = sysBaseAPI.getSubDepIdsByDepId(departId); //获取下级部门的部门id，自定义改造sysBaseAPI
        baseApiEntity.setSysOrgCode(sysOrgCode);
        baseApiEntity.setSubDepIdsList(subDepIdsList);
        String subDepSysOrgCodes = sysBaseAPI.getSubDepOrgCodesByDepId(departId); //直接获取下级部门的orgcode，自定义改造sysBaseAPI
        baseApiEntity.setSubDepSysOrgCodes(subDepSysOrgCodes);
        //userIdentity 用户身份字典码user_identity， 3教师 4学生 1普通用户 2上级部门负责人 5家长 6班级
        int userIdentity = loginUser.getUserIdentity();//获取当前登录用户身份：字典码 user_identity
        baseApiEntity.setUserIdentity(userIdentity);

        return baseApiEntity;
    }
}
